import { PageDom } from './page-object'
import { mpdComponentLibrary } from '../store/page-config'
import ant from './ant'
import element from './element'
import _ from 'lodash'
import layout from './layout'
import text from './text'
import { ComponentGroupInfo } from './page-object'
export * from './page-object'

const data: Array<ComponentGroupInfo> = [layout, text]
// 所有组件的map集合
const dataMap: { [key: string]: PageDom } = {}

// 初始化组件库数据
function initData(): void {
  let flag = false
  if (mpdComponentLibrary.length > 0) {
    const tmpLibrary: Array<ComponentGroupInfo> = _.cloneDeep(mpdComponentLibrary)
    // 合并配置项
    tmpLibrary.forEach(item => {
      let flag = true
      data.forEach(element => {
        if (element.id === item.id) {
          const tmpMap: { [key: string]: PageDom } = {}
          item.list.forEach(itemElement => {
            tmpMap[itemElement.id] = itemElement
          })
          element.list.forEach((listElement: PageDom) => {
            if (tmpMap.hasOwnProperty(listElement.id)) {
              const tmpItem: PageDom = tmpMap[listElement.id]
              for (const key in tmpItem) {
                listElement[key] = tmpItem[key]
              }
              delete tmpMap[listElement.id]
            }
          })
          for (const key in tmpMap) {
            element.list.push(tmpMap[key])
          }
          flag = false
        }
      })
      if (flag) {
        data.push(item)
      }
    })
    mpdComponentLibrary.splice(0, mpdComponentLibrary.length)
    flag = true
  }
  if (flag || Object.keys(dataMap).length === 0) {
    data.forEach((dataItem: ComponentGroupInfo) => {
      dataItem.list.forEach((listItem: PageDom) => {
        listItem.ext = listItem.ext || {}
        dataMap[listItem.id] = listItem
      })
    })
  }
}

// 获取组件库数据
export function getLibraryData(): Array<ComponentGroupInfo> {
  initData()
  return data
}

// 获取组件库map数据
export function getLibraryDataMap(key: string | undefined): PageDom | { [key: string]: PageDom } {
  initData()
  if (key) {
    return dataMap[key]
  }
  return dataMap
}

// 获得ant的配置
export function getAntConfig() {
  return ant
}
// 获得element的配置
export function getElementConfig() {
  return element
}

export default {
  // 获取组件库数据
  getLibraryData,
  // 获取组件库map数据
  getLibraryDataMap,
  // 获得ant的配置
  getAntConfig,
  // 获得element的配置
  getElementConfig
}
